<template>
  <el-container >
    <el-aside width="300px" v-loading="menuloading">
      <el-container>
        <el-header >
          <el-input placeholder="输入关键字进行过滤" v-model="menuFilterText" clearable></el-input>
        </el-header>
        <el-main class="nopadding">
          <el-tree ref="menu" class="menu" node-key="id" :data="menuList" :props="menuProps" draggable highlight-current
                   :expand-on-click-node="false" :default-expanded-keys="expandedKeys" check-strictly show-checkbox
                   :filter-node-method="menuFilterNode"
                   @node-click="menuClick" @node-drop="nodeDrop">

            <template #default="{node, data}">
							<span class="custom-tree-node">
								<span class="label">
									{{ node.label }}
								</span>
								<span class="do">
									<el-button :icon="plus" size="small" @click.stop="add(node, data)">添加</el-button>
								</span>
							</span>
            </template>

          </el-tree>
        </el-main>
        <el-footer style="height:51px;">
          <el-button type="primary" size="small" :icon="plus" @click="add()">添加</el-button>
          <el-button type="danger" size="small" plain :icon="deleteIcon" @click="delMenu">删除</el-button>
        </el-footer>
      </el-container>
    </el-aside>
    <el-container>
      <el-main class="nopadding" style="padding:20px;" ref="main">
        <save ref="save" :menu="menuList" @success="handleSaveSuccess"></save>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import {toRaw} from "vue";

let newMenuIndex = 1;
import save from './save.vue'
import { Delete, Edit, Search, Share, Upload,Plus } from '@element-plus/icons-vue'
export default {
  name: "settingMenu",
  components: {
    save
  },
  data() {
    return {
      Edit: Edit,
      deleteIcon: Delete,
      plus: Plus,


      menuloading: false,
      menuList: [],
      menuProps: {
        label: (data) => {
          return data.name
        }
      },
      expandedKeys: [],
      menuFilterText: "",
      selectId: "",
      selectData:"",
      searchObject:{
        appId:""
      }
    }
  },
  watch: {
    menuFilterText(val) {
      this.$refs.menu.filter(val);
    }
  },
  mounted() {
   this.searchObject.appId= this.$route.query.id;
    this.getMenu();
  },
  methods: {

    async handleSaveSuccess() {
      let res = await this.$http.form("/applicationMenu/root", this.searchObject);
      Object.assign(this.menuList, res.data);

      this.expandedKeys=[this.selectId];
      console.info(this.selectId)
      //this.$refs.menu.setCurrentNode(this.selectData,true)
      //this.$refs.menu.setCurrentKey(this.selectId+"",true);
    },
    //加载树数据
    async getMenu() {
      this.menuloading = true
      let res = await this.$http.form("/applicationMenu/root", this.searchObject);
      if (res.code === 0) {
        this.tableData = res;
      }
      this.loading = false;
      this.menuloading = false
      this.menuList = res.data;
    },
    //树点击
    menuClick(data, node) {
      const pid = node.level === 1 ? undefined : node.parent.data.id;

      this.$refs.save.setData(toRaw(data), pid)
      this.$refs.main.$el.scrollTop = 0
      this.selectId = data.id;
      this.selectData=node;
    },
    //树过滤
    menuFilterNode(value, data) {
      if (!value) return true;
      var targetText = data.name;
      return targetText.indexOf(value) !== -1;
    },
    //树拖拽
    async nodeDrop(draggingNode, dropNode, dropType) {
      this.$refs.save.setData({})
      console.info(dropType);
      console.info(draggingNode);
      console.info(dropNode)
      if (dropType==="inner"){
        console.info(draggingNode.data.id+" "+draggingNode.data.label);
        console.info(dropNode.data.id+" "+dropNode.data.label)
        let param={};
        param.id=draggingNode.data.id;
        param.parent=dropNode.data.id;

        await this.$http.form("/applicationMenu/update", param);

      }
      else if (dropType==="inner"){
        console.info(draggingNode.data.id+" "+draggingNode.data.label);
        console.info(dropNode.data.id+" "+dropNode.data.label)

        let param={};
        param.id=draggingNode.data.id;
        param.sortNum=dropNode.data.sortNum;

        await this.$http.form("/applicationMenu/update", param);

        let param1={};
        param1.id=dropNode.data.id;
        param1.sortNum=draggingNode.data.sortNum;

        await this.$http.form("/applicationMenu/update", param1);
      }else{
        console.info(draggingNode.data.id+" "+draggingNode.data.label);
        console.info(dropNode.data.id+" "+dropNode.data.label)

        let param={};
        param.menu=draggingNode.data.id;
        param.target=dropNode.data.id;
        param.dropType=dropType;

        await this.$http.form("/applicationMenu/drag", param);
      }
      // this.$message(`拖拽对象：${draggingNode.data.meta.title}, 释放对象：${dropNode.data.meta.title}, 释放对象的位置：${dropType}`)
    },
    //增加
    async add(node, data) {
      const newMenuName = "未命名" + newMenuIndex++;
      let newMenuData = {
        parent: data ? data.id : "",
        name: newMenuName,
        path: "",
        component: "",
        meta: {
          title: newMenuName,
          type: "menu"
        }
      };
      newMenuData.app=this.searchObject.appId;
      this.menuloading = true
      let res = await this.$http.form("/applicationMenu/create", newMenuData);

      this.menuloading = false
      newMenuData = res.data

      this.$refs.menu.append(newMenuData, node)
      this.$refs.menu.setCurrentKey(newMenuData.id)
      let pid = node ? node.data.id : ""
      this.$refs.save.setData(newMenuData, pid)

      this.selectId = newMenuData.id;
      this.selectData=node;
    },
    //删除菜单
    async delMenu() {
      var CheckedNodes = this.$refs.menu.getCheckedNodes()
      if (CheckedNodes.length == 0) {
        this.$message.warning("请选择需要删除的项")
        return false;
      }

      var confirm = await this.$confirm('确认删除已选择的菜单吗？', '提示', {
        type: 'warning',
        confirmButtonText: '删除',
        confirmButtonClass: 'el-button--danger'
      }).catch(() => {
      })
      if (confirm !== 'confirm') {
        return false
      }

      this.menuloading = true
      const reqData = {
        ids: CheckedNodes.map(item => item.id)
      };
      let res = null;
      for (let i = 0; i < reqData.ids.length; i++) {
        let item = reqData.ids[i];
        res = await this.$http.form("/applicationMenu/delete", {id: item});
      }
      this.menuloading = false

      if (res.code === 200) {
        CheckedNodes.forEach(item => {
          var node = this.$refs.menu.getNode(item)
          if (node.isCurrent) {
            this.$refs.save.setData({})
          }
          this.$refs.menu.remove(item)
        })
      } else {
        this.$message.warning(res.message)
      }
    }
  }
}
</script>

<style scoped>
.menu:deep(.el-tree-node__label) {
  display: flex;
  flex: 1;
  height: 100%;
}

.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  height: 100%;
  padding-right: 24px;
}

.custom-tree-node .label {
  display: flex;
  align-items: center;;
  height: 100%;
}

.custom-tree-node .label .el-tag {
  margin-left: 5px;
}

.custom-tree-node .do {
  display: none;
}

.custom-tree-node .do i {
  margin-left: 5px;
  color: #999;
}

.custom-tree-node .do i:hover {
  color: #333;
}

.custom-tree-node:hover .do {
  display: inline-block;
}
</style>
